//
//  ST_ProfileUserNameController.swift
//  BTVideo
//
//  Created by DouLei on 2019/10/8.
//  Copyright © 2019 DouLei. All rights reserved.
//

import UIKit
import RealmSwift
import SwifterSwift
import RxCocoa
import RxSwift


class ST_ProfileUserNameController: UIViewController,ST_RegisterRouteProtocol{
//    MARK: - life cycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = Color.white
        //RegisterStepManager.shared.step = 4
        view.addSubview(nickNameInfoBtn)
        nickNameInfoBtn.frame = CGRect.init(x: 150, y: 73-20+statusBarHeight, width: 153+10+30, height: 30)
        nickNameInfoBtn.alpha = 0.1
        
        view.addSubview(nickNameTextFiled)
        nickNameTextFiled.frame = CGRect.init(x: ScreenWidth + 100, y:self.nickNameInfoBtn.frame.maxY + 125, width: 265, height: 30)
        
        view.addSubview(next_btn)
        next_btn.frame = CGRect.init(x: ScreenWidth - 45 - 40, y: nickNameTextFiled.frame.maxY + 109, width: 45, height: 45)
        
//        TianRegisterStepManager.shared.pushStepLog(stepInt: 4)
        binding()
        
        bindNickname()
        
        //TianRegisterStepManager.shared.addHelperBtn(root_view: view)
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    
    
        UIView.zenly_animate(withDelay: 0.25, animations: {
            
            self.nickNameInfoBtn.x = 20
            
            self.nickNameInfoBtn.alpha = 1
            
        }) { (f) in
            
        }
        
        UIView.zenly_animate(withDelay: 0.35, animations: {

            self.nickNameTextFiled.center = CGPoint.init(x: ScreenWidth/2.0, y:             self.nickNameTextFiled.center.y)
            
        }) { (f) in
            
            UIView.zenly_animate(animations: {
                
                self.next_btn.alpha = 1
                
            }) { (f) in
                
                self.nickNameTextFiled.becomeFirstResponder()
            }
            
        }
        
    }
    
    fileprivate func binding(){
        
        Observable.combineLatest(pull_observer, SCComponets.config_component.boot_config_observer).subscribe(onNext: {[weak self] _ , state in
            
            if state == .finished{
                self?.pullRandom()
            }
            
        }).disposed(by: disposeBag)
        
    }
    
    
    @objc fileprivate func bindNickname(){
       
        if let user = ST_RegisterMonitor.shared.regist_response_account()?.userinfo,user.nickname.count > 0{
            
            nickNameTextFiled.text = user.nickname
            
            self.next_btn.isEnabled = nickNameTextFiled.text?.count ?? 0 > 0
        }else{
            
            pull_observer.onNext(())
        }
        
    }
    
    
    fileprivate func pullRandom(){
        
        JVrequest(PH.randomUserInfoApi,success:  { (json) in
            
            self.nickNameTextFiled.text = json["data"]["nickname"].stringValue
            
            self.next_btn.isEnabled = self.nickNameTextFiled.text?.count ?? 0 > 0
            
        } ,failure: { (code, err) in
            
        })
        
    }
    
//    MARK: - Properties
    
    var disposeBag = DisposeBag()
    
    fileprivate let pull_observer = PublishSubject<Void>()
    
    lazy var nickNameTextFiled:UITextField = {
            
        let control = UITextField.init()
        control.placeholder = "怎么称呼你？"
        control.setPlaceHolderTextColor(Color.init(hexString: "#999999")!)
        control.textColor = Color.init(hexString: "#333333")
        control.tintColor = Color.init(hexString: "#333333")
        control.textAlignment = .center
//        control.keyboardType = UIKeyboardType.numberPad
        
//        control.backgroundColor = Color.random
        
        control.font = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.semibold)
        
        control.delegate = self
        return control
        
    }()
    
     lazy var nickNameInfoBtn:UIButton = {
            
            let control = UIButton.init(type: UIButton.ButtonType.custom)
          control.setTitleForAllStates("嗨，你叫什么名字？")
          control.setTitleColor(UIColor.init(hexString: "#333333")!, for: UIControl.State.normal)
            control.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.semibold)
          control.setImageForAllStates(ST_ImageUtils.imageName("register_icon_emoji昵称")!)
            control.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 10, bottom: 0, right: 0)
//        control.backgroundColor = Color.random
        return control
    }()
    
    lazy var next_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)

        control.setImageForAllStates(ST_ImageUtils.imageName("register_bot_下一步")!)
        
        control.setImage(ST_ImageUtils.imageName("register_bot_下一步diss"), for: UIControl.State.disabled)
        
        control.addTarget(self, action: #selector(next_action), for: UIControl.Event.touchUpInside)
        
        control.isEnabled = false
        
        control.alpha = 0
        
        return control
    }()

    
//    MARK: - Event
    var next_action_closure:(()->())?
    
    @objc func next_action(){
      
        PlayFeedBack()
        
        pushNextRegisterController(parameters: ["nickname":self.nickNameTextFiled.text ?? ""])
        
    }
}

//MARK: - Delegate
extension ST_ProfileUserNameController:UITextFieldDelegate{
    
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        let currentString: NSString = textField.text! as NSString
        
        let newString: NSString =
            currentString.replacingCharacters(in: range, with: string) as NSString
            
        self.next_btn.isEnabled = newString.length > 0
        
        return newString.length <= 12
    }
    
}
